<template>
  <el-button 
    :type="buttonType" 
    :size="buttonSize"
    :icon="ArrowLeft"
    @click="handleBack"
    class="smart-back-button"
  >
    {{ buttonText }}
  </el-button>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getRouteHistory } from '../../router'

interface Props {
  buttonText?: string
  buttonType?: 'primary' | 'default' | 'text'
  buttonSize?: 'large' | 'default' | 'small'
  fallbackRoute?: string
}

const props = withDefaults(defineProps<Props>(), {
  buttonText: '返回',
  buttonType: 'default',
  buttonSize: 'default',
  fallbackRoute: '/'
})

const router = useRouter()

// 智能返回逻辑
const handleBack = () => {
  const history = getRouteHistory()
  
  // 过滤有效路由
  const validRoutes = history.filter(route => 
    !['/login', '/register', '/404', '/'].includes(route) &&
    !route.includes('error')
  )
  
  if (validRoutes.length > 0) {
    // 返回到最后一个有效页面
    const lastRoute = validRoutes[validRoutes.length - 1]
    
    // 如果返回的是/main页面，需要恢复Main页面的状态
    if (lastRoute === '/main') {
      // 检查是否有保存的Main页面状态
      const savedState = localStorage.getItem('mainPageState')
      if (savedState) {
        // 有保存的状态，直接跳转到/main，状态会在Main.vue中恢复
        router.push('/main')
        return
      }
    }
    
    router.push(lastRoute)
  } else {
    // 没有有效历史，使用fallback路由
    router.push(props.fallbackRoute)
  }
}

// 计算按钮文本
const buttonText = computed(() => {
  const history = getRouteHistory()
  const validRoutes = history.filter(route => 
    !['/login', '/register', '/404', '/'].includes(route) &&
    !route.includes('error')
  )
  
  if (validRoutes.length > 0) {
    return props.buttonText
  }
  
  return '返回首页'
})
</script>

<style scoped>
.smart-back-button {
  transition: all 0.3s ease;
}

.smart-back-button:hover {
  transform: translateX(-2px);
}
</style>
